package com.iflytek.iot.common.utils;

import java.nio.charset.Charset;
import java.security.MessageDigest;

/**
 * @author yu 2018/11/30.
 */
public class MD5Utils {

    private static final String hexDigIts[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * MD5加密，加密后返回的是小写，连调注意大小写
     *
     * @param plaintext 明文字符串
     * @return
     */
    public static String encrypt(String plaintext) {
        String resultString = null;
        try {
            resultString = new String(plaintext);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = HexUtils.byteArr2HexStr(md.digest(resultString.getBytes(Charset.defaultCharset())));
        } catch (Exception e) {
        }
        return resultString;
    }

    /**
     * 验证加密是否相同
     *
     * @param origin  需要加密的原字符
     * @param encoded 已加密的字符串
     * @return
     */
    public static boolean equals(String origin, String encoded) {
        if (StringUtils.isEmpty(encoded) || StringUtils.isEmpty(origin)) {
            return false;
        }
        return encrypt(origin).equals(encoded.toLowerCase());
    }
}
